package com.xydtech.web.controller.system;

import com.xydtech.common.annotation.Log;
import com.xydtech.common.constant.UserConstants;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.core.domain.entity.SysRole;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.core.text.Convert;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.poi.ExcelUtil;
import com.xydtech.ecard.imp.domain.EcardMerchantImport;
import com.xydtech.ecard.imp.service.IEcardMerchantImportService;
import com.xydtech.ecard.merchant.domain.*;
import com.xydtech.ecard.merchant.service.*;
import com.xydtech.framework.shiro.service.SysPasswordService;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysPostService;
import com.xydtech.system.service.ISysRoleService;
import com.xydtech.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author xydtech
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IEcardMerchantInfoService ecardMerchantInfoService;
    @Autowired
    private IEcardPersonInfoService ecardPersonInfoService;
    @Autowired
    private IEcardEnterpriseInfoService ecardEnterpriseInfoService;
    @Autowired
    private IEcardAgricultureInfoService ecardAgricultureInfoService;
    @Autowired
    private IEcardEnterpriseLocationService ecardEnterpriseLocationService;
    @Autowired
    private IEcardPersonAreaService ecardPersonAreaService;
    @Autowired
    private IEcardMerchantImportService ecardMerchantImportService;

    @Autowired
    private ISysDeptService sysDeptService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        String salt = getSalt();//盐值
        startPage();
        List<SysUser> list = userService.selectUserList(user, salt);
        return getDataTable(list);
    }

    /**
     * 导出
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        String salt = getSalt();//盐值
        List<SysUser> list = userService.selectUserList(user, salt);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        String salt = getSalt();//盐值
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport, getLoginName(), salt);
        return AjaxResult.success(message);
    }

    /**
     * 下载模板
     */
    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        String salt = getSalt();//盐值
        String phonenumber = user.getPhonenumber();
        String cardNum = user.getCardNum();
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user, salt))) {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(getLoginName());
        user.setPhonenumber(phonenumber);
        user.setCardNum(cardNum);
        return toAjax(userService.insertUser(user, salt));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        String salt = getSalt();//盐值
        userService.checkUserDataScope(userId, salt);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId, salt));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        mmap.put("extendPosts", postService.selectExtendPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        String salt = getSalt();//盐值
        String phonenumber = user.getPhonenumber();
        String cardNum = user.getCardNum();
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(ShiroUtils.getSysUser().getDeptId());
        //如果修改了用户的机构，判断该用户是否有所属的商户、农户/城镇居民、企业、新型农业主体、楼宇、网格，若有则提示先转交再进行修改机构
        SysUser oldUser = userService.selectUserById(user.getUserId(), salt);
        if (!StringUtils.objIsNullOrEmpty(oldUser.getDeptId()) && oldUser.getDeptId().compareTo(user.getDeptId()) != 0) {
            EcardMerchantInfo ecardMerchantInfo = new EcardMerchantInfo();
            ecardMerchantInfo.setUserId(user.getUserId());
            ecardMerchantInfo.setState(1);
            ecardMerchantInfo.setDictDeptId(sysDept.getDeptId());
            List<EcardMerchantInfo> ecardMerchantInfoList = ecardMerchantInfoService.selectEcardMerchantInfoList(ecardMerchantInfo);
            if (ecardMerchantInfoList.size() > 0) {
                return error("请先转交该用户的商户，再进行机构变更！");
            }
            EcardPersonInfo ecardPersonInfo = new EcardPersonInfo();
            ecardPersonInfo.setUserId(user.getUserId());
            ecardPersonInfo.setState(1);
            ecardPersonInfo.setDictDeptId(sysDept.getDeptId());
            List<EcardPersonInfo> ecardPersonInfoList = ecardPersonInfoService.selectEcardPersonInfoList(ecardPersonInfo, salt);
            if (ecardPersonInfoList.size() > 0) {
                return error("请先转交该用户的农户/城镇居民，再进行机构变更！");
            }
            EcardEnterpriseInfo enterpriseInfo = new EcardEnterpriseInfo();
            enterpriseInfo.setUserId(user.getUserId());
            enterpriseInfo.setState(1);
            enterpriseInfo.setDictDeptId(sysDept.getDeptId());
            List<EcardEnterpriseInfo> ecardEnterpriseInfoList = ecardEnterpriseInfoService.selectEcardEnterpriseInfoList(enterpriseInfo, salt);
            if (ecardEnterpriseInfoList.size() > 0) {
                return error("请先转交该用户的企业，再进行机构变更！");
            }
            EcardAgricultureInfo agricultureInfo = new EcardAgricultureInfo();
            agricultureInfo.setUserId(user.getUserId());
            agricultureInfo.setState(1);
            agricultureInfo.setDictDeptId(sysDept.getDeptId());
            List<EcardAgricultureInfo> ecardAgricultureInfoList = ecardAgricultureInfoService.selectEcardAgricultureInfoList(agricultureInfo, salt);
            if (ecardAgricultureInfoList.size() > 0) {
                return error("请先转交该用户的新型农业主体，再进行机构变更！");
            }
            EcardEnterpriseLocation enterpriseLocation = new EcardEnterpriseLocation();
            enterpriseLocation.setUserId(user.getUserId());
            enterpriseLocation.setState(1);
            enterpriseLocation.setDictDeptId(sysDept.getDeptId());
            List<EcardEnterpriseLocation> ecardEnterpriseLocationList = ecardEnterpriseLocationService.selectEcardEnterpriseLocationList(enterpriseLocation, salt);
            if (ecardEnterpriseLocationList.size() > 0) {
                return error("请先转交该用户的企业楼宇，再进行机构变更！");
            }
            EcardPersonArea personArea = new EcardPersonArea();
            personArea.setUserId(user.getUserId());
            personArea.setState(1);
            personArea.setDictDeptId(sysDept.getDeptId());
            List<EcardPersonArea> ecardPersonAreaList = ecardPersonAreaService.selectEcardPersonAreaList(personArea, salt);
            if (ecardPersonAreaList.size() > 0) {
                return error("请先转交该用户的个人网格，再进行机构变更！");
            }

            EcardMerchantImport ecardMerchantImport = new EcardMerchantImport();
            ecardMerchantImport.setUserCode(oldUser.getUserCode());
            ecardMerchantImport.setDeptId(oldUser.getDeptId());
            //ecardMerchantImport.setCorpId(sysDept.getDeptId());
            ecardMerchantImport.setSalt(salt);
            List<EcardMerchantImport> ecardMerchantImportlist = ecardMerchantImportService.selectEcardMerchantImportList(ecardMerchantImport);
            if(ecardMerchantImportlist.size() > 0){
                return error("请先转交该客户导入的个体工商户，再进行机构变更！");
            }
        }

        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user, salt))) {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getLoginName());
        user.setPhonenumber(phonenumber);
        user.setCardNum(cardNum);
        return toAjax(userService.updateUser(user, salt));
    }

    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        String salt = getSalt();//盐值
        mmap.put("user", userService.selectUserById(userId, salt));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        String salt = getSalt();//盐值
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user, salt) > 0) {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()) {
                setSysUser(userService.selectUserById(user.getUserId(), salt));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap) {
        String salt = getSalt();//盐值
        SysUser user = userService.selectUserById(userId, salt);
        // 获取用户所属的角色列表
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", user);
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, String roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        String salt = getSalt();//盐值
        return userService.checkPhoneUnique(user, salt);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 校验员工号码
     */
    @PostMapping("/checkUserCodeUnique")
    @ResponseBody
    public String checkUserCodeUnique(SysUser user) {
        return userService.checkUserCodeUnique(user);
    }

    /**
     * 校验微信号码
     */
    @PostMapping("/checkWechatCodeUnique")
    @ResponseBody
    public String checkWechatCodeUnique(SysUser user) {
        return userService.checkWechatCodeUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }
}